package com.ebt.m.wiki;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.data.bean.ExplainData;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.imageloader.ImageLoader;
import com.ebt.m.utils.imageloader.ImageLoaderUtil;
import com.ebt.m.widget.EBTProgress;
import com.ebt.m.widget.SubTitleView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by Damon.Han on 2017/10/20
 *
 * @author Damon
 */

public class ExplainWindow extends DialogFragment {

    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.loading)
    EBTProgress loading;
    @BindView(R.id.message)
    View message;
    @BindView(R.id.title1)
    SubTitleView title1;
    @BindView(R.id.dialog_header_right)
    ImageView dialogHeaderRight;
    @BindView(R.id.ref_img)
    ImageView refImg;
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    public static ExplainWindow newInstance(String title, String url) {
        ExplainWindow fragment = new ExplainWindow();
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putString("url", url);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.view_web_window, container, false);
        ButterKnife.bind(this, view);
        initDatas();
        return view;
    }


    protected void initDatas() {
        String title = getArguments().getString("title");
        String url = getArguments().getString("url");
        title1.setmTitleString(title);
        getData(url);
    }

    private void getData(String url) {
        Logger.e("url = " + url);
        if (url == null) {
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //fail
                e.printStackTrace();
                UIHelper.makeToast(getContext(), e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String jsonStr = response.body().string();
                        Logger.e("jsonStr = " + jsonStr);
                        jsonStr = jsonStr.substring(jsonStr.indexOf("(") + 1, jsonStr.length() - 1);
                        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                        Type type = new TypeToken<ExplainData>() {
                        }.getType();
                        ExplainData jsonBean = gson.fromJson(jsonStr, type);
                        String html = jsonBean.explain;
                        String htm = "<!DOCTYPE html>\n" +
                                "<html lang=\"en\">\n" +
                                "<head>\n" +
                                "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
                                "    <title>Title</title>\n" +
                                "    <link rel=\"stylesheet\" type=\"text/css\" href=\"http://mzyj.test.e-baotong.cn/css/wiki.css?v=11106120\">\n" +
                                "    <link rel=\"stylesheet\" type=\"text/css\" href=\"http://mzyj.test.e-baotong.cn/wiki/css/term/tiaokuan.css\">\n" +
                                "    <link rel=\"stylesheet\" type=\"text/css\" href=\"http://mzyj.test.e-baotong.cn/wiki/css/term/autoexplain.css\">\n" +
                                "</head>\n" + "<body>" + html +
                                "</body>\n" +
                                "</html>";
                        webview.post(new Runnable() {
                            @Override
                            public void run() {
                                if (!DataValidation.isEmpty(jsonBean.refImg)) {
                                    refImg.setVisibility(View.VISIBLE);
                                    ImageLoaderUtil.getInstance().loadImage(AppContext.getInstance(), new ImageLoader.Builder().url(jsonBean.refImg).imgView(refImg).build());
                                }
                                webview.loadData(htm, "text/html; charset=UTF-8", null);
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        Window dialogWindow = getDialog().getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(lp);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick(R.id.dialog_header_right)
    public void onViewClicked() {
        dismiss();
    }

}
